<template>
  <div class="app-container">
    <div v-if="!isManage">
      <div class="history">
        <el-button
          v-if="~accessable.indexOf('goods_flash:goods_current')"
          :type="postParams.history == 0 ? 'success' : 'info'"
          size="small"
          v-waves
          @click="now"
        >限时抢购</el-button>
        <el-button
          v-if="~accessable.indexOf('goods_flash:goods_history')"
          :type="postParams.history == 1 ? 'success' : 'info'"
          size="small"
          v-waves
          @click="history"
        >历史限时抢购</el-button>
      </div>
      <div class="filter-container">
        <el-button
          class="filter-item"
          v-if="~accessable.indexOf('goods_flash_sale:goods_add')"
          type="primary"
          size="small"
          v-waves
          icon="el-icon-plus"
          @click="handleUpdate(null)"
        >添加限时抢购</el-button>
        <el-input
          @keyup.enter.native="handleFilter"
          style="width: 200px;"
          clearable
          size="small"
          class="filter-item"
          placeholder="活动名称"
          v-model="postParams['title']"
        ></el-input>
        <el-select v-model="postParams['checkStatus']" clearable placeholder="审核状态" size="small">
          <el-option
            v-for="(item,index) in checkStatusList"
            :key="index"
            :label="item.label"
            :value="item.value"
          ></el-option>
        </el-select>
        <el-button
          class="filter-item"
          type="primary"
          size="small"
          v-waves
          icon="el-icon-search"
          @click="handleFilter"
        >搜索</el-button>
      </div>
      <div v-loading="loadingList">
        <el-row :gutter="20">
          <el-col :span="6" :xs="24" :lg="6" :sm="12" v-for="item in list" :key="item.id">
            <el-card class="box-card">
              <div slot="header" class="clearfix box-card-header">
                <div style="">{{item.title}}</div>
                <div style="padding-top:14px;">
                  <!-- <el-button style=" padding: 3px 0" v-if="~accessable.indexOf('goods_flash_sale:goods_reset_limit')" @click="resetBuyLimit(item)" type="text">清零限购记录</el-button> -->

                  <el-button
                    style=" padding: 3px 0"
                    v-if="~accessable.indexOf('goods_flash_sale:goods_modify')"
                    @click="handleUpdate(item)"
                    type="text"
                  >修改</el-button>
                  <el-button
                    style=" padding: 3px 0"
                    v-if="item.checkStatus!=5 && ~accessable.indexOf('goods_flash_sale:check_approve')"
                    @click="showCheckDialog(item)"
                    type="text"
                  >审核通过</el-button>
                  <el-button
                    style=" padding: 3px 0"
                    v-if="item.checkStatus!=10 && ~accessable.indexOf('goods_flash_sale:check_reject')"
                    @click="showCheckDialog(item,1)"
                    type="text"
                  >审核驳回</el-button>
                  <el-button
                    style=" padding: 3px 0"
                    v-if="item.status==0 && !isOutofDate(item.endTime) && ~accessable.indexOf('goods_flash_sale:goods_delete')"
                    @click="handleDelete(item)"
                    type="text"
                  >删除</el-button>
                </div>
              </div>
              <div class="text item">开始时间: {{item.startTime}}</div>
              <div class="text item">结束时间: {{item.endTime}}</div>
              <div class="text item">限定购买数量: {{item.buyLimitFlag?item.buyLimitNum:'(无)'}}</div>
              <div class="text item">是否使用商城库存: {{item.baseStockFlag?'是':'否'}}</div>
              <div class="text item" v-if="!item.baseStockFlag">批量设置库存数量: {{item.globalStockFlag?item.globalStockNum:'(无)'}}</div>
              <div class="text item">折扣类型: {{item.discountType|discountTypeFilter}}</div>
              <div
                class="text item"
                v-if="item.discountType == 2"
              >统一价格: ¥ {{item.money}} &nbsp;&nbsp; 统一积分: {{item.points}}</div>
              <div class="text item" v-if="item.discountType == 1">折扣百分比: {{item.discountPercent}}%</div>
              <div class="text item">状态 :
                <el-tag :type="item.status|statustagFilter">{{item.status|statusFilter}}</el-tag>
                <el-tag
                  :type="item.checkStatus|checkStatusTagFilter"
                >{{item.checkStatus|checkStatusFilter}}</el-tag>
              </div>
              <div class="bottom clearfix">
                <el-button
                  type="text"
                  v-if="~accessable.indexOf('goods_flash_sale:goods_relate_manage')"
                  style="float:right"
                  @click="manageGoods(item.id)"
                  class="button"
                >商品管理</el-button>
              </div>
              <div class="box-card-bg" :style="{backgroundImage:'url('+ imgUrl(item.cover)+')'}"></div>
            </el-card>
          </el-col>
        </el-row>
        <div class="pagination-container">
          <el-pagination
            background=""
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page.sync="postParams.page"
            :page-sizes="[10,20,30,50]"
            :page-size="postParams.limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
          ></el-pagination>
        </div>
      </div>
      <el-dialog :title="isEditing?'修改':'添加'" :visible.sync="dialogFormVisible" width="1000px">
        <el-form
          class="dialog-form"
          :rules="rules"
          ref="dataForm"
          :model="temp"
          label-position="left"
          label-width="140px"
        >
          <el-form-item label="活动名称" prop="title">
            <el-input v-model="temp.title" placeholder="活动名称"></el-input>
          </el-form-item>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="封面" prop="cover">
                <el-upload
                  class="avatar-uploader"
                  :action="UPLOAD_URL"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess('cover')"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="temp.cover" :src="temp.cover|absUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="LOGO" prop="logo">
                <el-upload
                  class="avatar-uploader"
                  :action="UPLOAD_URL"
                  :show-file-list="false"
                  :on-success="handleAvatarSuccess('logo')"
                  :before-upload="beforeAvatarUpload"
                >
                  <img v-if="temp.logo" :src="temp.logo|absUrl" class="avatar">
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="活动开始时间" prop="startTime">
                <el-date-picker
                  v-model="temp.startTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  align="right"
                  type="datetime"
                  placeholder="选择活动开始时间"
                  :picker-options="pickerOptions1"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="活动截止时间" prop="endTime">
                <el-date-picker
                  v-model="temp.endTime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  align="right"
                  type="datetime"
                  placeholder="选择活动截止时间"
                  :picker-options="pickerOptions1"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="折扣类型" prop="discountType">
                <el-select v-model="temp.discountType" placeholder="请选择">
                  <el-option
                    v-for="item in discountOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="折扣百分比" prop="discountPercent" v-if="temp.discountType==1">
                <el-input
                  type="number"
                  v-model="temp.discountPercent"
                  placeholder="比如80"
                  style="width:100px;"
                ></el-input>%
              </el-form-item>
              <el-form-item label="统一价" prop="money" v-if="temp.discountType==2">
                <el-input
                  type="number"
                  v-model="temp.money"
                  placeholder="请输入价格"
                  style="width:120px;"
                ></el-input>
              </el-form-item>
              <el-form-item label="统一积分" prop="points" v-if="temp.discountType==2">
                <el-input
                  type="number"
                  v-model="temp.points"
                  placeholder="请输入积分"
                  style="width:120px;"
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="活动状态" prop="status">
                <el-radio-group v-model="temp.status">
                  <el-radio
                    v-for="(item,value) in statusFilter"
                    :key="value"
                    :label="value"
                    :value="value"
                  >{{item}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="排序顺序" prop="sort">
                <el-input-number v-model="temp.sort" :min="0" label="排序顺序"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="限定购买数量" prop="buyLimitFlag">
                <el-radio-group v-model="temp.buyLimitFlag">
                  <el-radio
                    v-for="(item,value) in limitLabelFlagItems"
                    :key="value"
                    :label="value"
                    :value="value"
                  >{{item}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="temp.buyLimitFlag">
              <el-form-item label="限定数量" prop="buyLimitNum">
                <el-input-number v-model="temp.buyLimitNum" :min="0" label="限定数量"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="20">
              <el-form-item label="是否使用商城库存" prop="baseStockFlag">
                <el-radio-group v-model="temp.baseStockFlag">
                  <el-radio
                    v-for="(item,value) in baseStockFlagItems"
                    :key="value"
                    :label="value"
                    :value="value"
                  >{{item}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20" v-if="!temp.baseStockFlag">
            <el-col :span="12">
              <el-form-item label="是否批量设置库存" prop="globalStockFlag">
                <el-radio-group v-model="temp.globalStockFlag">
                  <el-radio
                    v-for="(item,value) in globalStockFlagItems"
                    :key="value"
                    :label="value"
                    :value="value"
                  >{{item}}</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="12" v-if="temp.globalStockFlag">
              <el-form-item label="批量设置库存数量" prop="globalStockNum">
                <el-input-number v-model="temp.globalStockNum" :min="0" label="批量设置库存数量"></el-input-number>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" :loading="submiting" @click="submitFormAction">确定</el-button>
        </div>
      </el-dialog>
    </div>
    <router-view></router-view>
    <el-dialog
      :title="isCheckRejecting?'审核驳回':'审核通过'"
      :visible.sync="isShowCheckDialog"
      width="800px"
    >
      <el-form
        class="dialog-form"
        :rules="rules"
        ref="checkDataForm"
        :model="checkData"
        label-position="left"
        label-width="140px"
      >
        <el-form-item label="审核意见" prop="checkRemark">
          <el-input type="textarea" :rows="6" v-model="checkData.checkRemark" placeholder="请输入审核意见"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="isShowCheckDialog = false">取消</el-button>
        <el-button
          type="primary"
          :loading="submiting"
          @click="isCheckRejecting?checkReject():checkApprove()"
        >确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { parseTime } from '../../filters/index'
let statusFilter = ['下线', '上线']
let limitLabelFlagItems = ['否', '是']
let statustagFilter = ['danger', 'success', 'info', 'warning']
let discountOptions = [
  {
    value: 1,
    label: '打折'
  },
  {
    value: 2,
    label: '统一价'
  }
]
export default {
  watch: {
    $route () {
      if (this.$route.name == 'goods_flash_sale:goods:list') {
        this.isManage = true
      } else {
        this.isManage = false
      }
    }
  },
  created () {
    if (this.$route.name === 'goods_flash_sale:goods:list') {
      this.isManage = true
    } else {
      this.isManage = false
    }
    this.loadData()
  },
  filters: {
    statusFilter (status) {
      return statusFilter[parseInt(status)]
    },
    checkStatusFilter (status) {
      status = parseInt(status)
      return ['待审核', '审核通过', '审核驳回'][status / 5]
    },
    checkStatusTagFilter (status) {
      status = parseInt(status)
      return ['danger', 'success', 'warning'][status / 5]
    },
    limitLabelFlagFilter (status) {
      return ['否', '是'][status || 0]
    },
    statustagFilter (status) {
      return statustagFilter[parseInt(status)]
    },
    discountTypeFilter (v) {
      let rt
      discountOptions.forEach(el => {
        if (el.value == v) {
          rt = el.label
        }
      })
      return rt
    }
  },
  methods: {
    history () {
      this.postParams.history = 1;
      this.handleFilter();
    },
    now () {
      this.postParams.history = 0;
      this.handleFilter();
    },
    resetBuyLimit (row) {
      this.$confirm('确定清零限购记录吗?', '提示').then(_ => {
        this.$post('/admin/goods_flash_sale/reset_buy_limit', {
          id: row.id
        }).then(data => {
          this.$$notify('清零成功')
        })
      })
    },
    isOutofDate (date) {
      return date < this.getNow()
    },
    handleFilter () {
      this.loadData()
    },
    handleDelete (row) {
      this.$confirm('确定删除该限时抢购活动吗?', '提示').then(_ => {
        this.$post('/admin/goods_flash_sale/delete', {
          id: row.id
        }).then(data => {
          this.loadData()
        })
      })
    },
    loadData () {
      this.loadingList = true
      this.$post('/admin/goods_flash_sale/list_all', this.postParams).then(
        data => {
          this.total = data.total
          data = data.rows
          data.forEach(el => {
            el.startTime && (el.startTime = parseTime(el.startTime))
            el.endTime && (el.endTime = parseTime(el.endTime))
          })
          this.loadingList = false
          this.list = data
        }
      )
    },
    manageGoods (id) {
      this.$router.push('/goods/goods_flash_sale/goods_list?id=' + id)
    },
    findNameByLabelId (id) {
      let rt = ''
      this.labelList.every(el => {
        if (el.id == id) {
          rt = el.name
          return false
        }
        return true
      })
      return rt
    },
    showCheckDialog (item, isCheckRejecting) {
      this.checkData.id = item.id
      this.checkData.checkRemark = ''
      this.isCheckRejecting = !!isCheckRejecting
      this.isShowCheckDialog = true
    },
    checkReject () {
      const row = this.checkData
      this.$post('/admin/goods_flash_sale/check_reject', {
        id: row.id,
        checkRemark: row.checkRemark
      }).then(data => {
        this.loadData()
        this.isShowCheckDialog = false
        this.$$notify()
      })
    },
    checkApprove () {
      const row = this.checkData
      this.$post('/admin/goods_flash_sale/check_approve', {
        id: row.id,
        checkRemark: row.checkRemark
      }).then(data => {
        this.loadData()
        this.isShowCheckDialog = false
        this.$$notify()
      })
    },
    submitFormAction () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          this.submiting = true
          let func = null
          if (this.isEditing) {
            func = this.$post('/admin/goods_flash_sale/modify', this.temp)
          } else {
            func = this.$post('/admin/goods_flash_sale/add', this.temp)
          }
          func
            .then(() => {
              this.submiting = false
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.loadData()
            })
            .catch(info => {
              this.submiting = false
              // this.$message({
              //   type: "warning",
              //   message: info || "更新失败!"
              // });
            })
        }
      })
    }
  },

  data () {
    return {
      isManage: false,
      discountOptions,
      dialogFormVisible: false,
      postParams: {
        page: 1,
        limit: 10,
        history: 0
      },
      labelList: [],
      isShowCheckDialog: false,
      checkData: {
        id: '',
        checkRemark: ''
      },
      total: 0,
      loadingList: true,
      checkStatusList: [
        {
          label: '待审核',
          value: 0
        },
        {
          label: '审核通过',
          value: 5
        },
        {
          label: '审核驳回',
          value: 10
        }
      ],
      isCheckRejecting: false,
      temp: {
        id: '',
        title: '',
        points: 0,
        startTime: '',
        discountType: '',
        buyLimitFlag: null,
        money: '',
        discountPercent: '',
        buyLimitNum: 0,
        endTime: '',
        limitLabelFlag: '',
        status: '',
        sort: 0,
        logo: '',
        globalStockFlag: 0,
        globalStockNum: 0,
        baseStockFlag: 0,
        cover: ''
      },
      baseStockFlagItems: ['否', '是'],
      globalStockFlagItems: ['否', '是'],
      limitLabelFlagItems,
      statusFilter: statusFilter,
      pickerOptions1: {
        shortcuts: [
          {
            text: '今天',
            onClick (picker) {
              picker.$emit('pick', new Date())
            }
          },
          {
            text: '昨天',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24)
              picker.$emit('pick', date)
            }
          },
          {
            text: '一周前',
            onClick (picker) {
              const date = new Date()
              date.setTime(date.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', date)
            }
          }
        ]
      },
      rules: {
        title: [
          {
            required: true,
            message: '特价活动名称不能为空',
            trigger: 'change'
          },
          {
            max: 50,
            message: '特价活动名称不能大于50个字',
            trigger: 'change'
          }
        ],
        globalStockFlag: [
          {
            required: true,
            message: '是否批量设置库存',
            trigger: 'change'
          }
        ],
        globalStockNum: [
          {
            required: true,
            message: '批量设置库存数量不能为空',
            trigger: 'change'
          },
          {
            min: 1,
            message: '批量设置库存数量必须大于0',
            trigger: 'change',
            type: 'number'
          }
        ],
        baseStockFlag: [
          {
            required: true,
            message: '是否使用商城库存',
            trigger: 'change'
          }
        ],
        startTime: [
          {
            required: true,
            message: '活动开始时间不能为空',
            trigger: 'change'
          }
        ],

        endTime: [
          {
            required: true,
            message: '活动截止时间不能为空',
            trigger: 'change'
          }
        ],
        discountType: [
          {
            required: true,
            message: '折扣类型必须指定',
            trigger: 'change'
          }
        ],

        discountPercent: [
          {
            required: true,
            message: '折扣比例必须指定',
            trigger: 'change'
          }
        ],
        money: [
          {
            required: true,
            message: '统一价必须指定',
            trigger: 'change'
          }
        ],
        cover: [
          {
            required: true,
            message: '请上传封面',
            trigger: 'change'
          }
        ],
        logo: [
          {
            required: true,
            message: '请上传logo',
            trigger: 'change'
          }
        ],
        points: [
          {
            required: true,
            message: '统一积分必须指定',
            trigger: 'change'
          }
        ],

        status: [
          {
            required: true,
            message: '请选中发布状态',
            trigger: 'change'
          }
        ],
        buyLimitFlag: [
          {
            required: true,
            message: '请选择是否限定购买数量',
            trigger: 'change'
          }
        ],
        buyLimitNum: [
          {
            required: true,
            message: '请填写限定购买数量',
            trigger: 'change'
          }
        ],
        limitLabelFlag: [
          {
            required: true,
            message: '请选择是否限定会员使用',
            trigger: 'change'
          }
        ]
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.item {
  line-height: 2.5em;
}

.box-card {
  margin-bottom: 20px;
  position: relative;
  z-index: 2;
}

.box-card-bg {
  position: absolute;
  background-position: center center;
  background-size: contain;
  background-repeat: no-repeat;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  display: block;
  opacity: 0.05;
  z-index: 0;
}
.box-card-header {
  position: relative;
  z-index: 2;
}
.box-card .item {
  position: relative;
  z-index: 2;
}
.box-card .bottom {
  position: relative;
  z-index: 2;
}
.history {
  margin-bottom: 8px;
}
</style>
